﻿using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace msBsc.AppLogic.DataAlc
{
    public class CBizDjkChargeTradingLog : CustBizObject
    {
        private CDmDjkChargeTradingLog m_CDmDjkChargeTradingLog = new CDmDjkChargeTradingLog();
        private CDmDjkChargeTradingLog oDmDjkChargeTradingLog
        {
            get { return m_CDmDjkChargeTradingLog; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizDjkChargeTradingLog()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmDjkChargeTradingLog.DJK_CHARGE_TRADING_LOG);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["CHARGE_TRADING_ID"];
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }
            if (drw["TRADING_NO"].ToString() == string.Empty)
            {
                drw["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("TRADING_NO", System.DateTime.Now.Year.ToString(), 8);
            }
            //drw["BUYER_DEL"] = false;
            //drw["BUYER_RATE_SID"] = "";

            return true;
        }
        public string GetNewTradingNo()
        {
            return "02" + msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            }
            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        {
            return true;
        }

        /// <summary>
        /// 添加订单支付记录
        /// </summary>
        /// <param name="strOrderId"></param>
        /// <returns></returns>
        public string[] AddCustomerTradingForPay(string strOrderId)
        {
            DataSet dsOrder = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_INFO WHERE ORDERS_INFO_ID='" + strOrderId + "' AND ORDER_BUYER_ID='" + msBsc.SvRef.UserInfo.Operator + "'");

            if (dsOrder == null
                || dsOrder.Tables[0].Rows.Count != 1)
            {
                return new string[] { "Error", "订单信息有误，请重新选择" };
            }

            DateTime startServceDt;
            if (!DateTime.TryParse(dsOrder.Tables[0].Rows[0]["ORDER_START_TIME"].ToString(), out startServceDt)
                || startServceDt < this.dtCurrDateTime)
            {
                return new string[] { "Error", "服务时间或付款时间错误" };
            }

            decimal payable = 0;
            if (!decimal.TryParse(dsOrder.Tables[0].Rows[0]["PAYABLE_AMT"].ToString(), out payable)
                || payable <= 0)
            {
                return new string[] { "Error", "订单价格错误，请检查订单信息" };
            }

            if ((dsOrder.Tables[0].Rows[0]["ORDER_DJACK_CHECK"].ToString().ToUpper() != "TRUE"
                && dsOrder.Tables[0].Rows[0]["ORDER_DJACK_CHECK"].ToString() != "1")
                || Convert.ToInt32(dsOrder.Tables[0].Rows[0]["ORDER_STATUS"]) != (int)msBsc.AppLogic.DataAlc.OrderStatusEnum.SolderChecked)
            {
                return new string[] { "Error", "当前订单状态不可支付，请确认订单信息" };
            }
            DataSet dsHasTrading = this.DataObj.QueryBySQL(@"SELECT * FROM " + this.TableName + " WHERE TRADING_NO='" + strOrderId.Replace("'", "").Replace(",", "','") + "' AND TRADING_TYPE_CID='购物' AND TRADING_SID='待支付'");

            if (dsHasTrading != null
                && dsHasTrading.Tables[0].Rows.Count > 0)
            {
                return new string[] { "OK", dsHasTrading.Tables[0].Rows[0]["CHARGE_TRADING_ID"].ToString() };
            }

            //获取当前买家信息
            DataSet dsBuyer = this.DataObj.QueryBySQL(@"SELECT CUSTOMER_REGISTER_ID,CUSTOMER_NICK FROM DJK_CUSTOMER_REGISTER WHERE CUSTOMER_REGISTER_ID='" + msBsc.SvRef.UserInfo.Operator + "'");
            if (dsBuyer == null || dsBuyer.Tables[0].Rows.Count != 1)
            {
                return new string[] { "Error", "当前登录用户不正确，不能进行交易" };
            }

            //获取订单卖家信息
            DataSet dsSolder = this.DataObj.QueryBySQL(@"SELECT CUSTOMER_REGISTER_ID,CUSTOMER_NICK FROM DJK_CUSTOMER_REGISTER WHERE CUSTOMER_REGISTER_ID='" + dsOrder.Tables[0].Rows[0]["ORDER_SOLDER_ID"] + "'");
            if (dsSolder == null || dsSolder.Tables[0].Rows.Count != 1)
            {
                return new string[] { "Error", "订单卖家信息有误，不能进行交易" };
            }

            string charge_trading_no = AddNewRow(dsBuyer.Tables[0].Rows[0]["CUSTOMER_REGISTER_ID"].ToString(), dsBuyer.Tables[0].Rows[0]["CUSTOMER_NICK"].ToString(), "支出", msBsc.SvRef.UserInfo.OperType, dsOrder.Tables[0].Rows[0]["ORDERS_INFO_ID"].ToString(), "游客支付定金", "购物", "system", "地接客平台", "在线支付", dsOrder.Tables[0].Rows[0]["PAYABLE_AMT"].ToString(), "待支付", "支付订购地接客车辆及服务所需费用的定金。地接客名称:[" + dsSolder.Tables[0].Rows[0]["CUSTOMER_NICK"].ToString() + "]", msBsc.SvRef.UserInfo.Operator, "");

            return new string[] { "OK", charge_trading_no };
        }

        /// <summary>
        /// 新增一行交易记录
        /// </summary>
        /// <param name="acc_no">买家账号</param>
        /// <param name="acc_nme">买家名称</param>
        /// <param name="pay_dir">支付流向(收入，支出)</param>
        /// <param name="user_type">用户类型(1:游客,2:地接客)</param>
        /// <param name="trading_no">交易编号(订单编号)</param>
        /// <param name="trading_nme">交易名称</param>
        /// <param name="trading_type">交易类型(购物，提现，退款，缴费(保证金)，扣点,结算)</param>
        /// <param name="oth_acc_no">卖家账号</param>
        /// <param name="oth_acc_nme">卖家名称</param>
        /// <param name="src_cid">支付类型(在线支付，商城账户)</param>
        /// <param name="trading_amt">支付金额</param>
        /// <param name="trading_sid">支付状态(待支付，已支付，已取消)</param>
        /// <param name="trading_desc">订单描述</param>
        /// <param name="init_usr">添加人</param>
        public string AddNewRow(string acc_no, string acc_nme, string pay_dir, string user_type, string trading_no, string trading_nme, string trading_type, string oth_acc_no, string oth_acc_nme, string src_cid, string trading_amt, string trading_sid, string trading_desc, string init_usr, string alipayAccount)
        {
            DataSet dsTrading = new CDmDjkChargeTradingLog();
            dsTrading.Tables[0].TableName = this.TableName;
            DateTime currentdt = this.dtCurrDateTime;

            DataRow dr = dsTrading.Tables[0].NewRow();
            dr["CHARGE_TRADING_ID"] = this.DataObj.NewID();
            dr["ACCOUNT_NO"] = acc_no;
            dr["ACCOUNT_NME"] = acc_nme;
            dr["USER_TYPE_CID"] = user_type;
            dr["PAY_DIR"] = pay_dir;
            dr["TRADING_NO"] = trading_no;
            dr["TRADING_NME"] = trading_nme;
            dr["TRADING_TYPE_CID"] = trading_type;
            dr["OTH_ACCOUNT_NO"] = oth_acc_no;
            dr["OTH_ACCOUNT_NME"] = oth_acc_nme;
            dr["CHARGE_SRC_CID"] = src_cid;
            dr["TRADING_AMT"] = trading_amt;
            dr["TRADING_SID"] = trading_sid;
            dr["TRADING_DESC"] = trading_desc;
            dr["SUBMIT_PAY_DT"] = currentdt;
            dr["IS_SPLIT"] = 0;
            dr["INITIAL_DT"] = currentdt;
            dr["INITIAL_USR"] = init_usr;
            dr["ALIPAY_TRADING_NO"] = alipayAccount;

            dsTrading.Tables[0].Rows.Add(dr);
            this.Update(dsTrading);

            return dr["CHARGE_TRADING_ID"].ToString();
        }


        /// <summary>
        /// 添加保证金支付记录
        /// </summary>
        /// <returns>结果：bool</returns>
        public string[] AddPromiseRecord()
        {
            if (!msBsc.SvRef.UserInfo.Online)
            {
                return new string[] { "FALSE", "当前无用户登录" };
            }

            if (msBsc.SvRef.UserInfo.OperType != "2")
            {
                return new string[] { "FALSE", "当前登录用户不是地接客" };
            }

            DataSet ds = new CBizCustomerBaseInfo().GetAliPayAndBank();
            decimal dep = 0, depStan = 0;
            decimal.TryParse(ds.Tables[0].Rows[0]["CUSTOMER_SECDEP_ACCOUNT"].ToString(), out dep);
            decimal.TryParse(System.Configuration.ConfigurationManager.AppSettings["PromBal"], out depStan);

            if (dep >= depStan)
            {
                return new string[] { "FALSE", "当前登录用户保证金充足，不需要缴纳" };
            }

            decimal depNeeds = depStan - dep;

            string trading_no = AddNewRow(msBsc.SvRef.UserInfo.Operator, msBsc.SvRef.UserInfo.OperatorName, "支出", msBsc.SvRef.UserInfo.OperType, GetNewTradingNo(), "地接客缴纳保证金", "缴费", "system", "地接客平台", "在线支付", depNeeds.ToString(), "待支付", "地接客向平台支付，保证金不足部分。", msBsc.SvRef.UserInfo.OperatorName, "");

            return new string[] { "TRUE", trading_no };
        }

        /// <summary>
        /// 获取订单是否完成支付，判断拆分支付的情况
        /// </summary>
        /// <param name="drw"></param>
        /// <returns></returns>
        private bool getIsCompletePay(DataRow drw)
        {
            if (drw["IS_SPLIT"].ToString() != "True")
            {
                return drw["TRADING_SID"].ToString() != "待支付";
            }
            else
            {
                DataSet ds = this.DataObj.QueryBySQL("SELECT TRADING_AMT FROM DJK_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND TRADING_NO = '" + drw["TRADING_NO"].ToString() + "'");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        private void doSqlForPayAfter(DataRow drw)
        {
            if (drw["TRADING_SID"].ToString() == "已支付" && drw["PAY_AFTER_SQL"].ToString() != string.Empty)
            {
                this.DataObj.ExecuteBySQL(drw["PAY_AFTER_SQL"].ToString());
            }

        }

        private void UpdateAccountChargeAmt(DataRow drw)
        {
            if (drw.RowState == DataRowState.Added && drw["TRADING_SID"].ToString() == "已支付"
                || drw.RowState == DataRowState.Modified && drw["TRADING_SID"].ToString() != drw["TRADING_SID", DataRowVersion.Original].ToString())
            {
                if (drw["TRADING_SID"].ToString() == "已支付")
                {
                    //账户增加余额
                    if (drw["TRADING_TYPE_CID"].ToString() == "充值" || drw["TRADING_TYPE_CID"].ToString() == "销售" || drw["TRADING_TYPE_CID"].ToString() == "退款")
                    {
                        if (drw["USER_TYPE_CID"].ToString() == "1")
                        {
                            this.DataObj.ExecuteBySQL("UPDATE SHP_COMMERCIAL_TENANT_INFO SET CHARGE_AMT=CHARGE_AMT+" + drw["TRADING_AMT"].ToString() + " WHERE COMM_TENANT_ID='" + drw["ACCOUNT_NO"].ToString() + "'");
                        }
                        else
                        {
                            this.DataObj.ExecuteBySQL("UPDATE SHP_CUSTOMER_INFO SET CHARGE_AMT=CHARGE_AMT+" + drw["TRADING_AMT"].ToString() + " WHERE USER_NME='" + drw["ACCOUNT_NO"].ToString() + "'");
                        }
                        //if (drw["TRADING_TYPE_CID"].ToString() == "充值")
                        //{
                        //    //客户充值送优币
                        //    if (drw["USER_TYPE_CID"].ToString() == "2")
                        //    {
                        //        using (CBizShpUMoneyTradingLog oumoney = new CBizShpUMoneyTradingLog())
                        //        {
                        //            oumoney.AddTradingLogForChongZhi(drw["ACCOUNT_NO"].ToString(), decimal.ToInt32((decimal)drw["TRADING_AMT"]));
                        //        }
                        //    } 
                        //}
                    }
                    //账户减少余额
                    if (drw["CHARGE_SRC_CID"].ToString() == "商城帐户" && drw["PAY_DIR"].ToString() == "支出")//.PAY_DIR='支出'
                    {
                        decimal decUserAmt = 0M;
                        if (drw["USER_TYPE_CID"].ToString() == "1")
                        {
                            using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo ouinfo = new AppLogic.DataAlc.CBizShpCommercialTenantInfo())
                            {
                                decUserAmt = ouinfo.GetShopChargeAmt(drw["ACCOUNT_NO"].ToString());
                            }
                        }
                        else
                        {
                            using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo ouinfo = new AppLogic.DataAlc.CBizShpCustomerInfo())
                            {
                                decUserAmt = ouinfo.GetUserChargeAmt(drw["ACCOUNT_NO"].ToString());
                            }
                        }
                        if ((decimal)drw["TRADING_AMT"] > decUserAmt)
                        {
                            throw new Exception("账户【" + drw["ACCOUNT_NO"].ToString() + "】剩余资金【" + decUserAmt.ToString() + "】小于本次支付金额【" + drw["TRADING_AMT"].ToString() + "】，操作失败！");
                        }

                        if (drw["USER_TYPE_CID"].ToString() == "1")
                        {

                            this.DataObj.ExecuteBySQL("UPDATE SHP_COMMERCIAL_TENANT_INFO SET CHARGE_AMT=CHARGE_AMT-" + drw["TRADING_AMT"].ToString() + " WHERE COMM_TENANT_ID='" + drw["ACCOUNT_NO"].ToString() + "'");
                        }
                        else
                        {
                            this.DataObj.ExecuteBySQL("UPDATE SHP_CUSTOMER_INFO SET CHARGE_AMT=CHARGE_AMT-" + drw["TRADING_AMT"].ToString() + " WHERE USER_NME='" + drw["ACCOUNT_NO"].ToString() + "'");
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 积分销售记录更新状态为已支付
        /// </summary>
        /// <param name="strOrderNo"></param>
        public void UpdateScoreSalseLogPayStatus(string strOrderNo)
        {
            using (CBizShpScoreSalesLog objss = new CBizShpScoreSalesLog())
            {
                DataSet dstm = objss.SelectByTradingNo(strOrderNo);
                if (dstm.Tables[0].Rows.Count > 0)
                {
                    dstm.Tables[0].Rows[0]["TRADING_SID"] = "已支付";
                    objss.Update(dstm);
                }
            }
        }



        /// <summary>
        /// 更新购物订单状态为已支付
        /// </summary>
        /// <param name="strOrderNos"></param>
        public void UpdateOrderPaySatus(string strOrderNo)
        {
            DataSet dstm = this.DataObj.QueryBySQL(@"
    SELECT
    B.*
    ,SRC_ALIPAY_TRADING_NO=V1.ALIPAY_TRADING_NO
    FROM 
    (
    SELECT TRADING_NO,ALIPAY_TRADING_NO=MAX(ALIPAY_TRADING_NO),TRADING_AMT=SUM(TRADING_AMT) FROM SHP_CHARGE_TRADING_LOG WHERE TRADING_SID='已支付' AND TRADING_TYPE_CID='购物' AND TRADING_NO = '" + strOrderNo + @"'  GROUP BY TRADING_NO
    ) AS V1
    LEFT OUTER JOIN SHP_ORDER_FORM B ON V1.TRADING_NO=B.ORDER_FORM_NO
    WHERE B.ORDER_FORM_ID IS NOT NULL AND V1.TRADING_AMT=B.PAID_AMT AND B.TRADE_STATUS_TXT='等待买家付款'
    ");
            dstm.Tables[0].TableName = "SHP_ORDER_FORM";

            for (int i = 0; i < dstm.Tables[0].Rows.Count; i++)
            {
                dstm.Tables[0].Rows[i]["TRADE_STATUS_TXT"] = "买家已付款";
                dstm.Tables[0].Rows[i]["ALIPAY_TRADING_NO"] = dstm.Tables[0].Rows[i]["ALIPAY_TRADING_NO"];
            }
            using (CBizShpOrderForm objorder = new CBizShpOrderForm())
            {
                objorder.Update(dstm);
            }
        }

        public DataSet SelectByIds(string strIdS)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  " + this.KeyFieldName + " IN  ('" + strIdS.Replace("'", "").Replace(",", "','") + "')");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectByAccountNo(string strAccountNo)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE ACCOUNT_NO='" + strAccountNo + "' ORDER BY INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectForFinder(string strTRADING_NO, string strACCOUNT_NO, string strINITIAL_DT_S, string strINITIAL_DT_E, string strTRADING_TYPE_CID, string strTRADING_SID, string strCHARGE_SRC_CID)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT A.*"
                + " ,ALIPAY_MAIL=CASE WHEN A.USER_TYPE_CID='1' THEN C.ALIPAY_MAIL ELSE B.ALIPAY_MAIL END "
                + " ,K.BANK_CDE "
                + " ,K.BANK_NME "
                + " ,BANK_ACCOUNT_NO=CASE WHEN A.USER_TYPE_CID='1' THEN C.BANK_ACCOUNT_NO ELSE B.BANK_ACCOUNT_NO END "
                + " ,BANK_ACCOUNT_NME=CASE WHEN A.USER_TYPE_CID='1' THEN C.BANK_ACCOUNT_NME ELSE B.BANK_ACCOUNT_NME END "
                + " FROM " + this.TableName + " A "
                + " LEFT OUTER JOIN SHP_CUSTOMER_INFO B ON A.USER_TYPE_CID<>'1' AND A.ACCOUNT_NO=B.USER_NME "
                + " LEFT OUTER JOIN SHP_COMMERCIAL_TENANT_INFO C ON A.USER_TYPE_CID='1' AND A.ACCOUNT_NO=C.COMM_TENANT_ID "
                + " LEFT OUTER JOIN BSE_BANK K ON A.USER_TYPE_CID='1' AND C.BANK_CDE=K.BANK_CDE OR A.USER_TYPE_CID<>'1' AND B.BANK_CDE=K.BANK_CDE "
                + " WHERE (1=1)"
                + (strTRADING_NO == string.Empty ? "" : " AND (A.TRADING_NO='" + strTRADING_NO + "')")
                + (strACCOUNT_NO == string.Empty ? "" : " AND (A.ACCOUNT_NO='" + strACCOUNT_NO + "')")
                + (strINITIAL_DT_S == string.Empty ? "" : " AND (A.DATEDIFF(DAY,INITIAL_DT,'" + strINITIAL_DT_S + "')<=0)")
                + (strINITIAL_DT_E == string.Empty ? "" : " AND (A.DATEDIFF(DAY,INITIAL_DT,'" + strINITIAL_DT_E + "')>=0)")
                + (strTRADING_TYPE_CID == string.Empty ? "" : " AND (A.TRADING_TYPE_CID='" + strTRADING_TYPE_CID + "')")
                + (strTRADING_SID == string.Empty ? "" : " AND (A.TRADING_SID='" + strTRADING_SID + "')")
                + (strCHARGE_SRC_CID == string.Empty ? "" : " AND (A.CHARGE_SRC_CID='" + strCHARGE_SRC_CID + "')")
                + "  ORDER BY A.INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }


        /// <summary>
        /// 付款到商城
        /// </summary>
        /// <param name="drOrder"></param>
        public DataRow PayChargeToMall(string strOrderNo, decimal decUserPaidAmt, decimal decOnlinePaidAmt)
        {
            strOrderNo = strOrderNo.Replace("'", "");
            if (strOrderNo == string.Empty || decUserPaidAmt == 0M && decOnlinePaidAmt == 0M)
            {
                throw new Exception("当前没有找到需要付款的订单，请返回重新选择！");
            }
            DataSet dsLog = this.DataObj.QueryBySQL("SELECT * FROM DJK_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND A.PAY_DIR='支出' AND TRADING_NO IN ('" + strOrderNo.Replace(",", "','") + "')");
            dsLog.Tables[0].TableName = "DJK_CHARGE_TRADING_LOG";
            for (int i = dsLog.Tables[0].Rows.Count - 1; i >= 0; i--)
            {
                DataRow drtlog = dsLog.Tables[0].Rows[i];
                if (decUserPaidAmt > 0)
                {
                    decimal decUserAmt = 0M;
                    if (drtlog["USER_TYPE_CID"].ToString() == "1")
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo ouinfo = new AppLogic.DataAlc.CBizShpCommercialTenantInfo())
                        {
                            decUserAmt = ouinfo.GetShopChargeAmt(drtlog["ACCOUNT_NO"].ToString());
                        }
                    }
                    else
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo ouinfo = new AppLogic.DataAlc.CBizShpCustomerInfo())
                        {
                            decUserAmt = ouinfo.GetUserChargeAmt(drtlog["ACCOUNT_NO"].ToString());
                        }
                    }
                    if (decUserPaidAmt > decUserAmt)
                    {
                        throw new Exception("当前账户金额过少，不能完成本次支付请求，请调整帐号支付金额后再继续提交付款请求！");
                    }
                    else
                    {
                        //增加账户支付的商城转账记录
                        if ((decimal)drtlog["TRADING_AMT"] <= decUserPaidAmt)//全部账户支付
                        {
                            drtlog["SUBMIT_PAY_DT"] = DateTime.Now;
                            drtlog["PAY_ARRIVE_DT"] = DateTime.Now;
                            drtlog["TRADING_SID"] = "已支付";
                            drtlog["CHARGE_SRC_CID"] = "商城帐户";
                            if (drtlog["TRADING_TYPE_CID"].ToString() == "")
                            {
                            }
                            decUserPaidAmt = decUserPaidAmt - (decimal)drtlog["TRADING_AMT"];
                        }
                        else//部分账户支付
                        {
                            DataRow drnewtrad2 = dsLog.Tables[0].NewRow();
                            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                            drnewtrad2["ACCOUNT_NO"] = drtlog["ACCOUNT_NO"];
                            drnewtrad2["ACCOUNT_NME"] = drtlog["ACCOUNT_NME"];
                            drnewtrad2["USER_TYPE_CID"] = drtlog["USER_TYPE_CID"];
                            drnewtrad2["PAY_DIR"] = drtlog["PAY_DIR"];//收付：收入、支出
                            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
                            drnewtrad2["TRADING_NO"] = drtlog["TRADING_NO"];
                            drnewtrad2["TRADING_NME"] = drtlog["TRADING_NME"];
                            drnewtrad2["TRADING_TYPE_CID"] = drtlog["TRADING_TYPE_CID"];//交易类型：购物，充值，缴费，提现，销售,购积分
                            drnewtrad2["OTH_ACCOUNT_NO"] = drtlog["OTH_ACCOUNT_NO"];
                            drnewtrad2["OTH_ACCOUNT_NME"] = drtlog["OTH_ACCOUNT_NME"];
                            drnewtrad2["TRADING_AMT"] = (decimal)drtlog["TRADING_AMT"] - decUserPaidAmt;
                            drnewtrad2["TRADING_SID"] = drtlog["TRADING_SID"];
                            drnewtrad2["TRADING_DESC"] = drtlog["TRADING_DESC"];
                            drnewtrad2["IS_SPLIT"] = true;
                            drnewtrad2["SUBMIT_PAY_DT"] = DateTime.Now;
                            drnewtrad2["PAY_ARRIVE_DT"] = DateTime.Now;
                            dsLog.Tables[0].Rows.Add(drnewtrad2);

                            drtlog["TRADING_AMT"] = decUserPaidAmt;
                            drtlog["TRADING_SID"] = "已支付";
                            drtlog["IS_SPLIT"] = true;
                            drtlog["CHARGE_SRC_CID"] = "商城帐户";

                            decUserPaidAmt = decUserPaidAmt - (decimal)drtlog["TRADING_AMT"];
                            decOnlinePaidAmt = decOnlinePaidAmt - (decimal)drnewtrad2["TRADING_AMT"];

                            if (i != 0)
                            {
                                throw new Exception("在线支付一次只能支付一个订单，请返回重新选择！");
                            }
                            else
                            {
                                if (decOnlinePaidAmt != 0)
                                {
                                    throw new Exception("在线支付的金额校验错误，请返回重新选择！");
                                }
                                this.Update(dsLog);
                                dsLog.AcceptChanges();
                                return drnewtrad2;
                            }
                        }

                        if (i == 0)
                        {
                            if (decUserPaidAmt > 0)
                            {
                                throw new Exception("账户支付的金额校验错误，请返回重新选择！");
                            }
                            else
                            {
                                this.Update(dsLog);
                                return null;
                            }
                        }
                    }

                }
                else
                {
                    if (i != 0)
                    {
                        throw new Exception("在线支付一次只能支付一个订单，请返回重新选择！");
                    }
                    else
                    {
                        decOnlinePaidAmt = decOnlinePaidAmt - (decimal)drtlog["TRADING_AMT"];
                        if (decOnlinePaidAmt != 0)
                        {
                            throw new Exception("在线支付的金额校验错误，请返回重新选择！");
                        }


                        drtlog["SUBMIT_PAY_DT"] = DateTime.Now;
                        this.Update(dsLog);
                        dsLog.AcceptChanges();
                        return drtlog;
                    }
                }
            }


            throw new Exception("当前没有找到需要付款的订单，请返回重新选择！");

        }

        /// <summary>
        /// 保存支付返回信息，返回OK
        /// </summary>
        /// <param name="trade_no"></param>
        /// <param name="order_no"></param>
        /// <param name="total_fee"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="buyer_email"></param>
        /// <param name="trade_status"></param>
        /// <param name="refund_status"></param>
        /// <returns></returns>
        public string doSaveAlipay(string trade_no, string order_no, string total_fee, string subject, string body, string buyer_email, string trade_status, string refund_status)
        {
            DataSet dsLog = this.DataObj.QueryBySQL("SELECT * FROM DJK_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND A.PAY_DIR='支出' AND TRADING_NO ='" + order_no + "' ORDER BY INITIAL_DT DESC");
            dsLog.Tables[0].TableName = this.TableName;


            string strErrmsg = "";
            string strTradingId = "";
            bool blPayed = false;
            bool blNeedLog = false;
            decimal decAmt = 0;
            if (dsLog.Tables[0].Rows.Count > 0)
            {
                strTradingId = dsLog.Tables[0].Rows[0]["CHARGE_TRADING_ID"].ToString();
                if (decimal.TryParse(total_fee, out decAmt))
                {
                    decAmt = decimal.Parse(total_fee);
                }
                else
                {
                    strErrmsg += "返回支付金额参数错误!";
                }
                if ((decimal)dsLog.Tables[0].Rows[0]["TRADING_AMT"] != decAmt)
                {
                    strErrmsg += "返回支付金额不等于待支付金额!";
                }


                if (string.IsNullOrEmpty(strErrmsg))
                {
                    blPayed = true;
                    blNeedLog = true;
                    dsLog.Tables[0].Rows[0]["ALIPAY_TRADING_NO"] = trade_no;
                    string trading_type = dsLog.Tables[0].Rows[0]["TRADING_TYPE_CID"].ToString();

                    if (trading_type == "购物")
                    {
                        SaveCustOrderCharge(dsLog);
                    }
                    else if (trading_type == "缴费")
                    {
                        SavePromiseCharge(dsLog);
                    }
                }
                else if (dsLog.Tables[0].Rows[0]["TRADING_DESC"].ToString().IndexOf(strErrmsg) == -1)
                {
                    blNeedLog = true;
                    dsLog.Tables[0].Rows[0]["TRADING_DESC"] = dsLog.Tables[0].Rows[0]["TRADING_DESC"].ToString() + strErrmsg;
                    this.Update(dsLog);
                }

            }
            else
            {
                return "OK";
            }

            if (blNeedLog)
            {
                //添加支付宝交易记录
                AddAliChargeRecord(strTradingId, trade_no, order_no, decAmt, subject, strErrmsg + body, buyer_email, trade_status, refund_status);
            }

            if (string.IsNullOrEmpty(strErrmsg))
            {
                strErrmsg = "OK";
            }
            return strErrmsg;
        }


        /// <summary>
        /// 保存手机端交易结果信息
        /// </summary>
        /// <param name="trade_no">支付宝交易号</param>
        /// <param name="order_no">内部订单编号</param>
        /// <returns></returns>
        public string doSavemAlipay(string trade_no, string order_no)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM DJK_CHARGE_TRADING_LOG A WHERE A.TRADING_NO='" + order_no.Replace(",", "','").Replace("'", "") + "' AND A.TRADING_SID='待支付' AND A.PAY_DIR='支出' ORDER BY A.INITIAL_DT DESC");

            ds.Tables[0].TableName = this.TableName;

            if (ds == null
                || ds.Tables[0].Rows.Count <= 0)
            {
                AddAliChargeRecord("", trade_no, order_no, 0, "", "", "", "success", "");
                return "订单不存在";
            }

            if (ds.Tables[0].Rows[0]["TRADING_TYPE_CID"].ToString() == "购物")
            {
                SaveCustOrderCharge(ds);
            }
            else if (ds.Tables[0].Rows[0]["TRADING_TYPE_CID"].ToString() == "缴费")
            {
                SavePromiseCharge(ds);
            }

            AddAliChargeRecord(ds.Tables[0].Rows[0]["CHARGE_TRADING_ID"].ToString(), trade_no, order_no, Convert.ToDecimal(ds.Tables[0].Rows[0]["TRADING_AMT"]), "", "", "", "success", "");
            return "OK";
        }

        /// <summary>
        /// 保存订单购物信息
        /// </summary>
        /// <param name="logDs"></param>
        /// <returns></returns>
        private void SaveCustOrderCharge(DataSet logDs)
        {
            string mdOrderMsg = string.Empty;

            DateTime currentDt = this.dtCurrDateTime;
            using (CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo())
            {
                if (objCBizOrdersInfo.CheckOrderPaied(logDs.Tables[0].Rows[0]["TRADING_NO"].ToString(), OrderStatusEnum.PaiedAll, currentDt) != "OK")
                {
                    mdOrderMsg = "更新订单信息错误";
                }
            }

            logDs.Tables[0].Rows[0]["TRADING_SID"] = "已支付";
            logDs.Tables[0].Rows[0]["PAY_ARRIVE_DT"] = currentDt;
            if (!string.IsNullOrEmpty(mdOrderMsg))
            {
                logDs.Tables[0].Rows[0]["TRADING_DESC"] = logDs.Tables[0].Rows[0]["TRADING_DESC"].ToString() + mdOrderMsg;
            }

            this.Update(logDs);
        }

        /// <summary>
        /// 保存提现记录
        /// </summary>
        /// <param name="logDs"></param>
        private string SaveCustDrawalsCharge(string tradingId)
        {
            if (string.IsNullOrEmpty(tradingId))
            {
                return "记录为空，不能提现";
            }

            DataSet logDs = SelectById(tradingId);

            if (logDs == null
                || logDs.Tables[0].Rows.Count <= 0)
            {
                return "记录为空，不能提现";
            }

            string mdOrderMsg = string.Empty;
            DateTime currentDt = this.dtCurrDateTime;
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                using (CBizDrawalsRecord objCBizDrawalsRecord = new CBizDrawalsRecord())
                {
                    if (!objCBizDrawalsRecord.ModifyDrawalsStatus(logDs.Tables[0].Rows[0]["TRADING_NO"].ToString(), msBsc.AppLogic.DataAlc.cls.CommonEnum.DrawalsEnum.paied, currentDt))
                    {
                        mdOrderMsg = "更新提现信息错误";
                    }
                }

                logDs.Tables[0].Rows[0]["TRADING_SID"] = "已支付";
                logDs.Tables[0].Rows[0]["PAY_ARRIVE_DT"] = currentDt;
                if (!string.IsNullOrEmpty(mdOrderMsg))
                {
                    logDs.Tables[0].Rows[0]["TRADING_DESC"] = logDs.Tables[0].Rows[0]["TRADING_DESC"].ToString() + mdOrderMsg;
                }

                this.Update(logDs);

                ts.Complete();
            }
            return "OK";
        }

        /// <summary>
        /// 保存保证金信息
        /// </summary>
        /// <param name="logDs"></param>
        private void SavePromiseCharge(DataSet logDs)
        {
            string mdOrderMsg = string.Empty;
            using (CBizCustomerBaseInfo objCBizCustomerBaseInfo = new CBizCustomerBaseInfo())
            {
                DataSet baseDs = objCBizCustomerBaseInfo.SelectById(logDs.Tables[0].Rows[0]["ACCOUNT_NO"].ToString());

                if (baseDs == null
                    || baseDs.Tables[0].Rows.Count <= 0)
                {
                    mdOrderMsg = "该用户不存在";
                }
                else
                {
                    baseDs.Tables[0].Rows[0]["CUSTOMER_SECDEP_ACCOUNT"] = Convert.ToDecimal(baseDs.Tables[0].Rows[0]["CUSTOMER_SECDEP_ACCOUNT"]) + Convert.ToDecimal(logDs.Tables[0].Rows[0]["TRADING_AMT"]);
                    objCBizCustomerBaseInfo.Update(baseDs);
                }
            }

            logDs.Tables[0].Rows[0]["TRADING_SID"] = "已支付";
            logDs.Tables[0].Rows[0]["PAY_ARRIVE_DT"] = this.dtCurrDateTime;
            if (!string.IsNullOrEmpty(mdOrderMsg))
            {
                logDs.Tables[0].Rows[0]["TRADING_DESC"] = logDs.Tables[0].Rows[0]["TRADING_DESC"].ToString() + mdOrderMsg;
            }

            this.Update(logDs);

        }

        /// <summary>
        /// 保存支付宝交易信息
        /// </summary>
        /// <param name="tradingId">支付记录编号</param>
        /// <param name="trade_no">订单编号</param>
        /// <param name="order_no"></param>
        /// <param name="decAmt"></param>
        /// <param name="subject"></param>
        /// <param name="tradingDesc"></param>
        /// <param name="buyer_email"></param>
        /// <param name="trade_status"></param>
        /// <param name="refund_status"></param>
        private void AddAliChargeRecord(string tradingId, string trade_no, string order_no, decimal decAmt, string subject, string tradingDesc, string buyer_email, string trade_status, string refund_status)
        {
            using (CBizShpChargeAlipayLog objalpay = new CBizShpChargeAlipayLog())
            {
                DataSet dsAlilog = new CDmShpChargeAlipayLog();

                DataRow drnew = dsAlilog.Tables[0].NewRow();
                drnew["ALIPAY_LOG_ID"] = this.DataObj.NewID();
                drnew["CHARGE_TRADING_ID"] = tradingId;
                drnew["ALIPAY_TRADING_NO"] = trade_no;
                drnew["OUT_TRADING_NO"] = order_no;
                drnew["TRADING_AMT"] = decAmt;
                drnew["TRADING_NME"] = subject;
                drnew["TRADING_DESC"] = tradingDesc;
                drnew["BUYER_EMAIL"] = buyer_email;
                drnew["TRADING_STATUS"] = trade_status;
                drnew["REFUND_STATUS"] = refund_status;
                dsAlilog.Tables[0].Rows.Add(drnew);
                objalpay.Update(dsAlilog);
            }
        }

        /// <summary>
        /// 根据订单编号获取交易记录信息
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns></returns>
        public DataSet GetTradingLogByOrderId(string orderId)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return null;
            }

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM " + this.TableName + " WHERE TRADING_NO='" + orderId.Replace("'", "").Replace(",", "','") + "'");

            ds.Tables[0].TableName = this.TableName;

            return ds;
        }

        /// <summary>
        /// 在线充值
        /// </summary>
        /// <param name="strChongzhiAMt"></param>
        /// <returns></returns>
        public DataRow AddTradingLogForChongzhi(string strChongzhiAMt, string strAccNo, string strAccNme, string strAccType)
        {
            decimal decAmt = 0;
            if (decimal.TryParse(strChongzhiAMt, out decAmt))
            {
                decAmt = decimal.Parse(strChongzhiAMt);
            }
            else
            {
                throw new Exception("请输入正确的金额！");
            }


            if (decAmt <= 0)
            {
                throw new Exception("请输入正确的金额！");
            }


            DataSet dstrad = new CDmShpChargeTradingLog();

            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();

            drnewtrad2["ACCOUNT_NO"] = strAccNo;
            drnewtrad2["ACCOUNT_NME"] = strAccNme;
            drnewtrad2["USER_TYPE_CID"] = strAccType;


            //if (msBsc.SvRef.ApplicationConst.Const.OperType == "1")
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[0];
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[1];
            //}
            //else
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.UserInfo.Operator;
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.UserInfo.Operator;
            //}
            //drnewtrad2["USER_TYPE_CID"] = msBsc.SvRef.ApplicationConst.Const.OperType;
            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
            drnewtrad2["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
            drnewtrad2["TRADING_NME"] = "充值到地接客商城";
            drnewtrad2["TRADING_TYPE_CID"] = "充值";//交易类型：购物，充值，缴费，提现，销售,购积分
            drnewtrad2["OTH_ACCOUNT_NO"] = "system";
            drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad2["TRADING_AMT"] = decAmt;
            drnewtrad2["TRADING_SID"] = "待支付";
            drnewtrad2["TRADING_DESC"] = "";
            dstrad.Tables[0].Rows.Add(drnewtrad2);

            this.Update(dstrad);

            return drnewtrad2;
            //}
        }


        /// <summary>
        /// 缴费，如缴纳保证金等
        /// </summary>
        /// <param name="strJiaofeiAMt"></param>
        /// <param name="strAccNo"></param>
        /// <param name="strAccNme"></param>
        /// <param name="strAccType"></param>
        /// <param name="strChargeDesc"></param>
        /// <returns></returns>
        public DataRow AddTradingLogForJiaofei(string strJiaofeiAMt, string strAccNo, string strAccNme, string strAccType, string strChargeDesc, string strPayAfterSql)
        {
            decimal decAmt = 0;
            if (decimal.TryParse(strJiaofeiAMt, out decAmt))
            {
                decAmt = decimal.Parse(strJiaofeiAMt);
            }
            else
            {
                throw new Exception("请输入正确的金额！");
            }


            if (decAmt <= 0)
            {
                throw new Exception("请输入正确的金额！");
            }
            if (strChargeDesc == string.Empty)
            {
                strChargeDesc = "缴费到地接客商城";
            }

            DataSet dstrad = new CDmDjkChargeTradingLog();

            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();

            drnewtrad2["ACCOUNT_NO"] = strAccNo;
            drnewtrad2["ACCOUNT_NME"] = strAccNme;
            drnewtrad2["USER_TYPE_CID"] = strAccType;


            //if (msBsc.SvRef.ApplicationConst.Const.OperType == "1")
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[0];
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[1];
            //}
            //else
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.UserInfo.Operator;
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.UserInfo.Operator;
            //}
            //drnewtrad2["USER_TYPE_CID"] = msBsc.SvRef.ApplicationConst.Const.OperType;
            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
            drnewtrad2["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
            drnewtrad2["TRADING_NME"] = strChargeDesc;
            drnewtrad2["TRADING_TYPE_CID"] = "缴费";//交易类型：购物，充值，缴费，提现，销售,购积分
            drnewtrad2["OTH_ACCOUNT_NO"] = "system";
            drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad2["TRADING_AMT"] = decAmt;
            drnewtrad2["TRADING_SID"] = "待支付";
            drnewtrad2["TRADING_DESC"] = "";
            drnewtrad2["PAY_AFTER_SQL"] = strPayAfterSql;
            dstrad.Tables[0].Rows.Add(drnewtrad2);

            this.Update(dstrad);

            return drnewtrad2;
            //}
        }

        /// <summary>
        /// 生成付款账单，费用来源：商城帐户，在线支付 ,推广账户
        /// </summary>
        /// <param name="drOrder"></param>
        public void AddTradingLogForAddOrder(DataRow drOrder)
        {
            if ((decimal)drOrder["PAID_AMT"] <= 0)
            {
                return;
            }
            DataSet dstrad = new CDmShpChargeTradingLog();

            //客户增加积分
            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad2["ACCOUNT_NO"] = drOrder["USER_NME"];
            drnewtrad2["ACCOUNT_NME"] = drOrder["USER_NME"];
            drnewtrad2["USER_TYPE_CID"] = "2";
            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
            drnewtrad2["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad2["TRADING_NME"] = drOrder["ORDER_FORM_NME"];
            drnewtrad2["TRADING_TYPE_CID"] = "购物";//交易类型：购物，充值，缴费，提现，销售,购积分
            drnewtrad2["OTH_ACCOUNT_NO"] = "system";
            drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad2["TRADING_AMT"] = drOrder["PAID_AMT"];
            drnewtrad2["TRADING_SID"] = "待支付";
            drnewtrad2["TRADING_DESC"] = "";
            dstrad.Tables[0].Rows.Add(drnewtrad2);

            this.Update(dstrad);
        }


        public DataSet SelectByTradingNo(string strTradingNo, string strTradingType)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE TRADING_NO='" + strTradingNo + "' AND TRADING_TYPE_CID='" + strTradingType + "' ORDER BY INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        //未签收前退款
        public void AddTradingLogForOrderReturn(DataRow drOrder)
        {
            if ((decimal)drOrder["PAID_AMT"] <= 0)
            {
                return;
            }

            DataSet dstm = this.SelectByTradingNo(drOrder["ORDER_FORM_NO"].ToString(), "购物");

            //待支付时取消支付
            //已支付时生成退款账单
            for (int i = dstm.Tables[0].Rows.Count - 1; i >= 0; i--)
            {
                DataRow drtlog = dstm.Tables[0].Rows[i];
                if (dstm.Tables[0].Rows[i]["TRADING_SID"].ToString() == "待支付")
                {
                    dstm.Tables[0].Rows[i]["TRADING_SID"] = "已取消";
                }
                if (dstm.Tables[0].Rows[i]["TRADING_SID"].ToString() == "已支付")
                {
                    //dstm.Tables[0].Rows[i]["TRADING_SID"] = "已取消";
                    //DataSet dstrad = new CDmShpChargeTradingLog();

                    DataRow drnewtrad2 = dstm.Tables[0].NewRow();
                    drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                    drnewtrad2["ACCOUNT_NO"] = drtlog["ACCOUNT_NO"];
                    drnewtrad2["ACCOUNT_NME"] = drtlog["ACCOUNT_NME"];
                    drnewtrad2["USER_TYPE_CID"] = drtlog["USER_TYPE_CID"];
                    drnewtrad2["PAY_DIR"] = "收入";//收付：收入、支出
                    drnewtrad2["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付，推广账户
                    drnewtrad2["TRADING_NO"] = drtlog["TRADING_NO"];
                    drnewtrad2["TRADING_NME"] = drtlog["TRADING_NME"];
                    drnewtrad2["TRADING_TYPE_CID"] = "退款";//交易类型：购物，充值，缴费，提现，销售,购积分
                    drnewtrad2["OTH_ACCOUNT_NO"] = "system";
                    drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
                    drnewtrad2["TRADING_AMT"] = drtlog["TRADING_AMT"];
                    drnewtrad2["TRADING_SID"] = "已支付";
                    drnewtrad2["TRADING_DESC"] = "购物退款到账户余额";
                    drnewtrad2["SUBMIT_PAY_DT"] = DateTime.Now;
                    drnewtrad2["PAY_ARRIVE_DT"] = DateTime.Now;


                    dstm.Tables[0].Rows.Add(drnewtrad2);


                }
            }
            if (dstm.HasChanges())
            {
                this.Update(dstm);
            }

            //}
        }

        /// <summary>
        /// 自动批量结算订单
        /// </summary>
        /// <returns></returns>
        public string AutoCloseAccount()
        {
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                using (CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo())
                {
                    DataSet dsOrders = objCBizOrdersInfo.GetReadyToCloseOrder();

                    if (dsOrders == null
                        || dsOrders.Tables[0].Rows.Count <= 0)
                    {
                        return "OK";
                    }

                    string strMsg = string.Empty;

                    DataSet dsResult = CloseAllAccount(dsOrders, out strMsg);

                    objCBizOrdersInfo.Update(dsResult);

                    ts.Complete();

                    return string.IsNullOrEmpty(strMsg) ? "OK" : strMsg;
                }
            }
        }

        /// <summary>
        /// 手动单笔结算订单信息
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns>"OK",[错误消息]</returns>
        public string ManualCloseAccount(string orderId)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return "订单信息有误！";
            }

            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                using (CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo())
                {
                    string strMsg = string.Empty;
                    DataSet dsOrders = objCBizOrdersInfo.SelectById(orderId);
                    if (dsOrders == null
                        || dsOrders.Tables[0].Rows.Count != 1)
                    {
                        return "订单信息有误";
                    }

                    if (Convert.ToInt32(dsOrders.Tables[0].Rows[0]["ORDER_STATUS"]) != (int)OrderStatusEnum.PaiedAll
                        && Convert.ToInt32(dsOrders.Tables[0].Rows[0]["ORDER_STATUS"]) != (int)OrderStatusEnum.RefundCanceled)
                    {
                        return "该订单信息有误，不允许进行确认服务";
                    }

                    DataSet dsResult = CloseAllAccount(dsOrders, out strMsg);

                    objCBizOrdersInfo.Update(dsResult);
                    ts.Complete();
                    return string.IsNullOrEmpty(strMsg) ? "OK" : strMsg;
                }
            }
        }

        /// <summary>
        /// 结算订单
        /// </summary>
        /// <param name="dsOrders"></param>
        /// <returns></returns>
        public DataSet CloseAllAccount(DataSet dsOrders, out string strMsg)
        {
            strMsg = string.Empty;
            DataSet dsPayForDjk = new CDmDjkChargeTradingLog();


            for (int i = 0; i < dsOrders.Tables[0].Rows.Count; i++)
            {
                using (CBizCustomerBaseInfo objCBizCustomerBaseInfo = new CBizCustomerBaseInfo())
                {
                    DataSet dsBase = objCBizCustomerBaseInfo.SelectById(dsOrders.Tables[0].Rows[i]["ORDER_SOLDER_ID"].ToString());

                    string chkResult = CmfOrderPayIsEQ(dsOrders.Tables[0].Rows[i]["ORDERS_INFO_ID"].ToString(), Convert.ToDecimal(dsOrders.Tables[0].Rows[i]["PAYABLE_AMT"]));
                    if (chkResult != "OK")
                    {
                        strMsg += dsOrders.Tables[0].Rows[i]["ORDERS_INFO_ID"].ToString() + ":" + chkResult + ",";
                        continue;
                    }

                    DateTime currentTime = this.dtCurrDateTime;

                    DataRow dr1 = dsPayForDjk.Tables[0].NewRow();
                    dr1["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                    dr1["ACCOUNT_NO"] = "system";
                    dr1["ACCOUNT_NME"] = "地接客平台";
                    dr1["USER_TYPE_CID"] = 0;
                    dr1["PAY_DIR"] = "收入";
                    dr1["TRADING_NO"] = dsOrders.Tables[0].Rows[i]["ORDERS_INFO_ID"];
                    dr1["TRADING_NME"] = "订单结算给地接客";
                    dr1["TRADING_TYPE_CID"] = "结算";
                    dr1["ALIPAY_TRADING_NO"] = "system";
                    dr1["OTH_ACCOUNT_NO"] = dsOrders.Tables[0].Rows[i]["ORDER_SOLDER_ID"];
                    dr1["OTH_ACCOUNT_NME"] = dsOrders.Tables[0].Rows[i]["ORDER_SOLDER_ID"];
                    dr1["CHARGE_SRC_CID"] = "平台账户";
                    dr1["TRADING_AMT"] = dsOrders.Tables[0].Rows[i]["PAYABLE_AMT"];
                    dr1["TRADING_SID"] = "已支付";
                    dr1["TRADING_DESC"] = "订单结算，地接客收益";
                    dr1["SUBMIT_PAY_DT"] = currentTime;
                    dr1["IS_SPLIT"] = 0;
                    dr1["INITIAL_DT"] = currentTime;
                    dr1["INITIAL_USR"] = msBsc.SvRef.UserInfo.Operator;
                    dsPayForDjk.Tables[0].Rows.Add(dr1);

                    DataRow dr2 = dsPayForDjk.Tables[0].NewRow();
                    dr2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                    dr2["ACCOUNT_NO"] = dsOrders.Tables[0].Rows[i]["ORDER_SOLDER_ID"];
                    dr2["ACCOUNT_NME"] = dsOrders.Tables[0].Rows[i]["ORDER_SOLDER_ID"];
                    dr2["USER_TYPE_CID"] = 2;
                    dr2["PAY_DIR"] = "支出";
                    dr2["TRADING_NO"] = dsOrders.Tables[0].Rows[i]["ORDERS_INFO_ID"];
                    dr2["TRADING_NME"] = "地接客支付交易手续费";
                    dr2["TRADING_TYPE_CID"] = "扣点";
                    dr2["ALIPAY_TRADING_NO"] = "system";
                    dr2["OTH_ACCOUNT_NO"] = "system";
                    dr2["OTH_ACCOUNT_NME"] = "地接客平台";
                    dr2["CHARGE_SRC_CID"] = "平台账户";
                    dr2["TRADING_AMT"] = (decimal)(Convert.ToDouble(dsOrders.Tables[0].Rows[i]["PAYABLE_AMT"]) * 0.05);
                    dr2["TRADING_SID"] = "已支付";
                    dr2["TRADING_DESC"] = "完成交易，地接客每笔订单向平台缴纳手续费";
                    dr2["SUBMIT_PAY_DT"] = currentTime;
                    dr2["IS_SPLIT"] = 0;
                    dr2["INITIAL_DT"] = currentTime;
                    dr2["INITIAL_USR"] = "system";
                    dsPayForDjk.Tables[0].Rows.Add(dr2);

                    dsBase.Tables[0].Rows[0]["CUSTOMER_DRAWALS_ACCOUNT"] = Convert.ToDecimal(dsBase.Tables[0].Rows[0]["CUSTOMER_DRAWALS_ACCOUNT"] == DBNull.Value ? "0" : dsBase.Tables[0].Rows[0]["CUSTOMER_DRAWALS_ACCOUNT"].ToString()) + (decimal)(Convert.ToDouble(dsOrders.Tables[0].Rows[i]["PAYABLE_AMT"]) * 0.95);

                    dsOrders.Tables[0].Rows[i]["IS_PAIEDFOR_DJK"] = 1;
                    dsOrders.Tables[0].Rows[i]["PAIEDFOR_DJK_DT"] = this.dtCurrDateTime;
                    dsOrders.Tables[0].Rows[i]["ORDER_STATUS"] = (int)OrderStatusEnum.Finished;

                    objCBizCustomerBaseInfo.Update(dsBase);

                }
            }

            this.Update(dsPayForDjk);
            return dsOrders;
        }

        /// <summary>
        /// 判断订单应付金额和实际支付金额是否相同
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="pay_able_amt">订单订单金额</param>
        /// <returns></returns>
        private string CmfOrderPayIsEQ(string orderId, decimal pay_able_amt)
        {
            DataSet dsTrad = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_CHARGE_TRADING_LOG A WHERE A.TRADING_NO='" + orderId + "' AND A.TRADING_TYPE_CID='购物' AND A.PAY_DIR='支出' ORDER BY A.INITIAL_DT DESC");

            if (dsTrad == null
                || dsTrad.Tables[0].Rows.Count <= 0)
            {
                return "该订单不存在交易记录";
            }

            if (dsTrad.Tables[0].Rows[0]["TRADING_SID"].ToString() != "已支付")
            {
                return "该订单状态为:" + dsTrad.Tables[0].Rows[0]["TRADING_SID"].ToString();
            }

            if (Convert.ToDecimal(dsTrad.Tables[0].Rows[0]["TRADING_AMT"]) != pay_able_amt)
            {
                return "该订单应付金额与实际支付金额不等";
            }

            return "OK";
        }

        /// <summary>
        /// 退款处理
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns></returns>
        public string RefundCust(string orderId)
        {
            DataSet dsOrder = null;
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                using (CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo())
                {
                    dsOrder = objCBizOrdersInfo.SelectById(orderId);
                    if (dsOrder == null || dsOrder.Tables[0].Rows.Count <= 0)
                    {
                        return "该订单不存在，请检查";
                    }

                    if (Convert.ToInt32(dsOrder.Tables[0].Rows[0]["ORDER_STATUS"]) != (int)OrderStatusEnum.SurePayBack)
                    {
                        return "该订单状态，不能进行退款";
                    }
                    using (CBizCustomerRefund objCBizCustomerRefund = new CBizCustomerRefund())
                    {
                        DataSet dsRefund = objCBizCustomerRefund.GetRefundInfoByOrderId(orderId);

                        if (dsRefund == null
                            || dsRefund.Tables[0].Rows.Count <= 0)
                        {
                            return "该订单没有进行退款申请";
                        }

                        if (Convert.ToInt32(dsRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"]) != (int)RefundStatus.CheckedRefund)
                        {
                            return "该订单当前状态不允许退款，请确认地接客是否已确认退款";
                        }

                        #region 处理交易记录
                        DataSet dsTrad = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_CHARGE_TRADING_LOG A WHERE A.TRADING_NO='" + orderId + "' AND A.TRADING_TYPE_CID='购物' AND A.PAY_DIR='支出' ORDER BY A.INITIAL_DT DESC");
                        dsTrad.Tables[0].TableName = this.TableName;


                        if (dsTrad == null
                            || dsTrad.Tables[0].Rows.Count <= 0)
                        {
                            return "该订单不存在交易记录";
                        }

                        if (dsTrad.Tables[0].Rows[0]["TRADING_SID"].ToString() != "已支付")
                        {
                            return "该订单状态为:" + dsTrad.Tables[0].Rows[0]["TRADING_SID"].ToString();
                        }

                        if (Convert.ToDecimal(dsTrad.Tables[0].Rows[0]["TRADING_AMT"]) != Convert.ToDecimal(dsOrder.Tables[0].Rows[0]["PAYABLE_AMT"]))
                        {
                            return "该订单应付金额与实际支付金额不等";
                        }

                        decimal refund_amt = 0;
                        DateTime appDt, startDt;

                        if (!DateTime.TryParse(dsRefund.Tables[0].Rows[0]["APPLY_REFUND_TIME"].ToString(), out appDt)
                            || !DateTime.TryParse(dsOrder.Tables[0].Rows[0]["ORDER_START_TIME"].ToString(), out startDt))
                        {
                            return "订单时间信息异常";
                        }

                        TimeSpan tis = appDt - startDt;

                        if (tis.Days < 15)
                        {
                            //扣除地接客保证金
                            if (DeductionProm(dsOrder.Tables[0].Rows[0]["ORDER_SOLDER_ID"].ToString(), 200) != "OK")
                            {
                                return "退款失败，扣除卖家保证金失败";
                            }
                        }
                        DataSet dsAlipay;
                        using (CBizShpChargeAlipayLog objalpay = new CBizShpChargeAlipayLog())
                        {
                            dsAlipay = objalpay.SelectByChargeTradingId(dsTrad.Tables[0].Rows[0]["CHARGE_TRADING_ID"].ToString());
                        }
                        string trading_id = AddNewRow("system", "地接客平台", "支出", "0", dsOrder.Tables[0].Rows[0]["ORDERS_INFO_ID"].ToString(), "向买家退款", "退款", dsOrder.Tables[0].Rows[0]["ORDER_BUYER_ID"].ToString(), dsOrder.Tables[0].Rows[0]["ORDER_BUYER_ID"].ToString(), "商城账户", dsTrad.Tables[0].Rows[0]["TRADING_AMT"].ToString(), "已支付", "按照平台规则对已支付的订单进行退款", msBsc.SvRef.UserInfo.Operator, dsAlipay.Tables[0].Rows[0]["BUYER_EMAIL"].ToString());

                        using (CBizCustomerBaseInfo objCBizCustomerBaseInfo = new CBizCustomerBaseInfo())
                        {
                            DataSet dsBaseInfo = objCBizCustomerBaseInfo.SelectById(dsOrder.Tables[0].Rows[0]["ORDER_BUYER_ID"].ToString());

                            dsBaseInfo.Tables[0].Rows[0]["CUSTOMER_DRAWALS_ACCOUNT"] = Convert.ToDecimal(dsBaseInfo.Tables[0].Rows[0]["CUSTOMER_DRAWALS_ACCOUNT"] == DBNull.Value ? "0" : dsBaseInfo.Tables[0].Rows[0]["CUSTOMER_DRAWALS_ACCOUNT"]) + Convert.ToDecimal(dsTrad.Tables[0].Rows[0]["TRADING_AMT"]);

                            dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] = (int)OrderStatusEnum.FinishRefund;

                            dsRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] = (int)RefundStatus.Finished;
                            dsRefund.Tables[0].Rows[0]["REFUND_FINISH_TIME"] = this.dtCurrDateTime;

                            objCBizCustomerBaseInfo.Update(dsBaseInfo);
                            objCBizOrdersInfo.Update(dsOrder);
                            objCBizCustomerRefund.Update(dsRefund);

                        }
                        ts.Complete();
                        #endregion
                    }
                }
            }
            return "OK";
        }

        /// <summary>
        /// 扣除保证金
        /// </summary>
        /// <param name="custId">用户Id</param>
        /// <param name="dedu_amt">扣除金额</param>
        /// <returns></returns>
        private string DeductionProm(string custId, decimal dedu_amt)
        {
            if (string.IsNullOrEmpty(custId)
                || dedu_amt <= 0)
            {
                return "Error";
            }

            using (CBizDjackSpecieInfo objCBizDjackSpecieInfo = new CBizDjackSpecieInfo())
            {
                DataSet dsSpecie = objCBizDjackSpecieInfo.SelectById(custId);

                if (dsSpecie == null
                    || dsSpecie.Tables[0].Rows.Count <= 0)
                {
                    return "Error";
                }

                if (Convert.ToInt32(dsSpecie.Tables[0].Rows[0]["DJACK_TRADING_NUMBER"] == DBNull.Value ? "0" : dsSpecie.Tables[0].Rows[0]["DJACK_TRADING_NUMBER"].ToString()) <= 3)
                {
                    return "OK";
                }
            }

            using (CBizCustomerBaseInfo objCBizCustomerBaseInfo = new CBizCustomerBaseInfo())
            {
                DataSet ds = objCBizCustomerBaseInfo.SelectById(custId);

                if (ds == null
                    || ds.Tables[0].Rows.Count <= 0)
                {
                    return "Error";
                }

                ds.Tables[0].Rows[0]["CUSTOMER_SECDEP_ACCOUNT"] = Convert.ToDecimal(ds.Tables[0].Rows[0]["CUSTOMER_SECDEP_ACCOUNT"] == DBNull.Value ? "0" : ds.Tables[0].Rows[0]["CUSTOMER_SECDEP_ACCOUNT"].ToString()) - dedu_amt;
                objCBizCustomerBaseInfo.Update(ds);

                AddNewRow(custId, custId, "支出", "2", GetNewTradingNo(), "卖家扣除保证金", "缴费", "system", "地接客平台", "商城账户", dedu_amt.ToString(), "已支付", "卖家违规操作，扣除保证金200元", "admin", "");
            }

            return "OK";
        }

        /// <summary>
        /// 后台查询交易账单信息
        /// </summary>
        /// <param name="tradingno"></param>
        /// <param name="tradingstdt"></param>
        /// <param name="tradingstodt"></param>
        /// <param name="sictype"></param>
        /// <param name="sicstatus"></param>
        /// <param name="sicsec"></param>
        /// <returns></returns>
        public DataSet GetTradingLogInfoForSys(string tradingno, string tradingstdt, string tradingstodt, string sictype, string sicstatus, string sicsec)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("tradingno", ParameterDirection.Input, EDbType.String, 36, tradingno));
            parmCollection.Add(new CDbParm("tradingstdt", ParameterDirection.Input, EDbType.String, 30, tradingstdt));
            parmCollection.Add(new CDbParm("tradingstodt", ParameterDirection.Input, EDbType.String, 30, tradingstodt));
            parmCollection.Add(new CDbParm("sictype", ParameterDirection.Input, EDbType.String, 20, sictype));
            parmCollection.Add(new CDbParm("sicstatus", ParameterDirection.Input, EDbType.String, 20, sicstatus));
            parmCollection.Add(new CDbParm("sicsec", ParameterDirection.Input, EDbType.String, 20, sicsec));


            DataSet ds = this.DataObj.QueryBySP("DJK_SELECT_TRADING_LOG_FOR_VIEW", parmCollection);
            ds.Tables[0].TableName = this.TableName;

            return ds;
        }
    }
}
